package com.fanxj.Utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.model.DeleteObjectsRequest;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Service
public class OSSService {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.image-path}")
    private String imagePath;

    public String uploadFile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 指定要上传到的文件夹路径
        String folderPath = "images/images/"; // 这就是文件夹路径

        String fileName = folderPath+System.currentTimeMillis() + "_" + file.getOriginalFilename();

        try (InputStream inputStream = file.getInputStream()) {
            ossClient.putObject(bucketName, fileName, inputStream);
//            return "https://" + bucketName + "." + endpoint.replace("https://", "")+  "/" + fileName;
            return "/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClient.shutdown();
        }
    }

    public String deleteFile(String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try{
            // 执行删除操作
            ossClient.deleteObject(bucketName, fileName);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        } finally {
            ossClient.shutdown();
        }
    }

    public String generateOssSignature() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置签名过期时间
        Date expiration = new Date(System.currentTimeMillis() +32400);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, imagePath);
        request.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(request);
        ossClient.shutdown();
//        // 提取签名部分
        String signature = url.toString().split("\\?")[1];
        return url.toString();
    }
}